#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

#include <unistd.h>

using namespace std;

#define N 2
#define NUM 1024

// child
void Writer(int wfd)
{
    string s = "hello, I am a child";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUM];

    while (true)
    {
        buffer[0] = 0; // 字符串清空,只是为了提醒阅读代码的人,把数组当成字符串
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
        //cout << buffer << endl;
        write(wfd,buffer,strlen(buffer));
       sleep(1);
       cout << number << endl;
       //if (number >= 5) break;
    }
}

// father
void Reader(int rfd)
{
    char buffer[NUM];

    int cnt =  0;
    while (true)
    {
       // sleep(5);

        buffer[0] = 0;
        ssize_t n = read(rfd,buffer,sizeof(buffer));

        if (n > 0)
        {
            buffer[n] = 0;
            cout << "father get a message[" << getpid() << "]# " << buffer << endl;
        }
        else if (n == 0)
        {
            break;
        }
        else
        {
            break;
        }
        
        cnt++;

        if (cnt >= 5) break;
      //  sleep(3);
        

      //  cout << "n : " << n << endl;

       // sleep(5);
    }
    
}

int main()
{

    int pipefd[N] = {0};

    int n = pipe(pipefd);

    if (n < 0)
    {
        return 1;
    }

    // cout << "pipefd[0]: " << pipefd[0] << " ,pipefd[1]: " << pipefd[1] << endl;

    pid_t id = fork();

    if (id < 0)
        return 2;

    if (id == 0)
    {
        // child

        close(pipefd[0]);

        Writer(pipefd[1]);

        close(pipefd[1]);
        exit(1);
    }
    // praent
    close(pipefd[1]);
    

    Reader(pipefd[0]);
    close(pipefd[0]);

    cout << "father close fd" << endl;

    sleep(10);

    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if (rid < 0) return 3;

    cout << "child exit code: " << WEXITSTATUS(status) << "exit singal" << (status&0x7F) << endl;

    // close(pipefd[0]);
    return 0;
}